from random import randint

from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework import status

from libs.yuntongxun.sms import CCP
from verifications.serializers import RegisterSMSCodeSerializer


class RegisterImageCodeView(APIView):
    def get(self, request, image_code_id):
        text, image = captcha.captcha.generate_captcha()
        redis_conn = get_redis_connection('code') #redis连接的库号
        redis_conn.setex('img_%s' % image_code_id, 60, text)
        return HttpResponse(image,content_type='image/jpeg')

class RegisterSMSCodeView(GenericAPIView):
    serializer_class = RegisterSMSCodeSerializer

    def get(self, request, mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        redis_conn = get_redis_connection('code')
        if redis_conn.get('sms_flag_%s' % mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)
        sms_code = '%06d' % randint(0, 999999)
        redis_conn.setex('sms_%s' % mobile, 5 * 60, sms_code)
        redis_conn.setex('sms_flag_%s' % mobile, 60, 1)
        ccp = CCP()
        ccp.send_template_sms(mobile, [sms_code, 5], 1)
        return Response({'message': 'ok'})
